﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace HelloWorld.Utils
{
    public class ApiResponseFilter: IActionFilter
    {
        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            // 动作执行前操作
        }

        public void OnActionExecuted(ActionExecutedContext context)
        {
            if (context.Result is ObjectResult objectResult)
            {
                var apiResponse = new ApiResponse(objectResult.StatusCode ?? 200, objectResult.Value, "success");
                context.Result = new ObjectResult(apiResponse)
                {
                    StatusCode = objectResult.StatusCode
                };
            }
            else if (context.Result is EmptyResult)
            {
                var apiResponse = new ApiResponse(200, null, "success");
                context.Result = new ObjectResult(apiResponse)
                {
                    StatusCode = 200
                };
            }
        }
    }
}
